/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.ss.config.configrations;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.cache.CacheType;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.zfes.snowy.core.exceptions.AppRuntimeException;

@Configuration
@EnableConfigurationProperties(CacheProperties.class)
public class SnowyCacaheConfiguration {
	
	@Autowired
	private CacheProperties cacheProperties;
	@Autowired
	private RedisTemplate<?,?> redisTemplate;
	
	@Bean(name = "ehcache")
	@Lazy(true)
	public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){  
	    EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();  
	    ehCacheManagerFactoryBean.setShared(true);  
	    return ehCacheManagerFactoryBean;  
	}  
	@Lazy(true) 
	@Bean(name = "cacheManager")
	public CacheManager ehCacheCacheManager(){  
		CacheType cacheType=cacheProperties.getType();
		switch (cacheType) {
		case EHCACHE:
			EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();  
		    ehCacheCacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
		    return ehCacheCacheManager;
		case REDIS:
		    return new RedisCacheManager(redisTemplate);
		default:
			throw new AppRuntimeException("CacheType is not support ");
		}
	} 
	

}
